﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;

using System.Data.SQLite;
using System.Collections.Generic;

namespace System.Data.SQLiteProvider
{
    public class SQLiteSqlService
    {
        //数据库连接字符串(web.config来配置)，可以动态更改connectionString支持多数据库.
        protected string currentConnectionString = "";

        public System.Data.SQLite.SQLiteConnectionStringBuilder ConnectionStringBuilder { get; set; }

        public SQLiteSqlService(System.Data.SQLite.SQLiteConnectionStringBuilder conBuilder)
        {
            if (conBuilder != null)
            {
                this.ConnectionStringBuilder = conBuilder;
                currentConnectionString = conBuilder.ConnectionString;
            }
            else
            {
                throw new Exception("ConnectionStringBuilder is null");
            }
        }

        #region 公用方法

        public int GetMaxID(string fieldName, string tableName)
        {
            string strsql = "select max(" + fieldName + ")+1 from " + tableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        public bool Exists(string sql)
        {
            object obj = GetSingle(sql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool Exists(string sql, params SQLiteParameter[] para)
        {
            object obj = GetSingle(sql, para);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string sql)
        {
            if (!string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                {
                    try
                    {
                        conn.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        conn.Close();
                        throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="sql">多条SQL语句</param>		
        public bool ExecuteSqlTran(IList sql)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            var res = false;
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                conn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = conn;
                SQLiteTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    if (sql != null && sql.Count > 0)
                    {
                        for (int n = 0; n < sql.Count; n++)
                        {
                            string strsql = sql[n].ToString();
                            if (strsql.Trim().Length > 1)
                            {
                                cmd.CommandText = strsql;
                                cmd.ExecuteNonQuery();
                            }
                        }
                        tx.Commit();
                        res = true;
                    }
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    tx.Rollback();
                    throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
            }
            return res;
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string sql, string content)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(sql, conn);
                SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    conn.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                    conn.Close();
                }
            }
        }
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSqlInsertImg(string sql, byte[] fs)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(sql, conn);
                SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    conn.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                    conn.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="sql">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string sql)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                {
                    try
                    {
                        conn.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        conn.Close();
                        throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句，返回SQLiteDataReader
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public SQLiteDataReader ExecuteReader(string sql)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(sql, conn);
                try
                {
                    conn.Open();
                    SQLiteDataReader myReader = cmd.ExecuteReader();
                    return myReader;
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sql)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    conn.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(sql, conn);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
                return ds;
            }
        }

        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string sql, params SQLiteParameter[] para)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, conn, null, sql, para);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="sql">SQL语句的哈希表（key为sql语句，value是该语句的SQLiteParameter[]）</param>
        public void ExecuteSqlTran(Hashtable sql)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                conn.Open();
                using (SQLiteTransaction trans = conn.BeginTransaction())
                {
                    SQLiteCommand cmd = new SQLiteCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in sql)
                        {
                            string cmdText = myDE.Key.ToString();
                            SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();

                            trans.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="sqll">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string sqll, params SQLiteParameter[] para)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, conn, null, sqll, para);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                    finally
                    {
                        if (conn != null)
                        {
                            conn.Close();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回SQLiteDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] para)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand();
                try
                {
                    PrepareCommand(cmd, conn, null, sql, para);
                    SQLiteDataReader myReader = cmd.ExecuteReader();
                    cmd.Parameters.Clear();
                    return myReader;
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sql, params SQLiteParameter[] para)
        {
            if (string.IsNullOrEmpty(currentConnectionString))
            {
                throw new Exception("currentConnectionString is null");
            }
            using (SQLiteConnection conn = new SQLiteConnection(currentConnectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand();
                PrepareCommand(cmd, conn, null, sql, para);
                using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        throw new Exception(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                    return ds;
                }
            }
        }

        #endregion

        #region tools


        public bool DeleteTableAllData(string tableName)
        {
            var res = false;
            var sql = new List<string>(){
                "delete from "+ tableName,
            };
            res = this.ExecuteSqlTran(sql);
            return res;
        }

        public bool DeleteTableAllData(IList<string> tableName)
        {
            var res = false;
            var sql = new List<string>();
            foreach (var item in tableName)
            {
                sql.Add("delete from " + item);
            }
            res = this.ExecuteSqlTran(sql);
            return res;
        }

        public bool DeleteTableAllDataAndSetSeqZero(string tableName)
        {
            var res = false;
            var sql = new List<string>(){
                "delete from "+tableName,
                "update sqlite_sequence set seq=0 where name='"+tableName+"'"
            };
            res = this.ExecuteSqlTran(sql);
            return res;
        }

        public bool DeleteTableAllDataAndSetSeqZero(IList<string> tableName)
        {
            var res = false;
            var sql = new List<string>();
            foreach (var item in tableName)
            {
                sql.Add("delete from " + item);
                sql.Add("update sqlite_sequence set seq=0 where name='" + item + "'");
            }
            res = this.ExecuteSqlTran(sql);
            return res;
        }

        public bool ReleaseDbSpace()
        {
            var res = false;
            var sql = "VACUUM";
            if (this.ExecuteSql(sql) > 0)
            {
                res = true;
            }
            return res;
        }

        #endregion

        #region util

        protected void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] para)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (para != null)
            {
                foreach (SQLiteParameter parm in para)
                    cmd.Parameters.Add(parm);
            }
        }

        #endregion
    }
}
